package com.link.base.base.image.controller;

import com.link.base.base.image.model.Image;
import com.link.base.base.image.service.AppImageService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.UploadImgInfo;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.ImageUtil;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: LiQun
 * created: 2018/8/20
 * comments: app图像
 */
@Controller
@RequestMapping("/link/image")
public class AppImageController extends BasicController<Image> {

    @Resource
    private AppImageService appImageService;
    @Resource
    private KeyGenerateService keyGenerateService;


    @RequestMapping(value = "/queryByExamplePage", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Map<String, Object> queryByExamplePage(@JsonParam Image image, HttpSession session, HttpServletRequest request,
                                                  HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        String module = request.getParameter("module");
        Long parentId = Long.parseLong(request.getParameter("parentid"));
        Image i = new Image();
        i.setParentid(parentId);
        i.setModule(module);
        try {
            List<Image> list = appImageService.queryAll(i);
            result.put("success", true);
            result.put("result", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.toString());
        }
        return result;
    }

    @Override
    @RequestMapping(value = "/upsert", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upsert(@RequestBody Image record, HttpSession session, HttpServletRequest request,
                                      HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Long accntId = record.getId();
            Boolean isNew;
            String newStatus = "NEW";
            if (null != accntId) {
                if (newStatus.equals(record.getRow_status())) {
                    isNew = true;
                } else {
                    isNew = false;
                }
            } else {
                accntId = keyGenerateService.keyGenerate();
                record.setId(accntId);
                isNew = true;
            }
            String url = record.getUrl();
            record.setUrl("");
            if (url != null && !"".equals(url)) {
                UploadImgInfo ui = ImageUtil.saveImageAndLessImage(url, record.getModule(), String.valueOf(record.getParentid()));
                record.setUrl(ui.getFilePath());
                record.setFileType("jpg");
                record.setSmallurl(ui.getFileLessPath());
                record.setBigurl(ui.getBigfilePath());
                record.setAttachmentSize(ui.getFileSize());
                record.setAttachmentName(ui.getFileName());
                appImageService.insert(record);
                record = appImageService.queryById(record);
            } else {
                if (!isNew) {
                    appImageService.update(record);
                }
            }
            result.put("success", true);
            result.put("result", record);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 用于项目系统反馈功能保存图片
     *
     * @author 李莹
     * @date 2019/12/24 06:43
     */
    @RequestMapping(value = "/insertOuterImage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> insertOuterImage(@RequestBody Image record, HttpSession session, HttpServletRequest request,
                                      HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Long accntId = record.getId();
            if (null == accntId) {
                accntId = keyGenerateService.keyGenerate();
                record.setId(accntId);
            }
            String url = record.getUrl();
            record.setUrl("");
            if (url != null && !"".equals(url)) {
                UploadImgInfo ui = ImageUtil.saveImageAndLessImage(url, record.getModule(), String.valueOf(record.getParentid()));
                record.setUrl(ui.getFilePath());
                record.setFileType("jpg");
                record.setSmallurl(ui.getFileLessPath());
                record.setBigurl(ui.getBigfilePath());
                record.setAttachmentSize(ui.getFileSize());
                record.setAttachmentName(ui.getFileName());
                appImageService.insertOuterImage(record);
                record = appImageService.queryById(record);
            }
            result.put("success", true);
            result.put("result", record);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/getId", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getId(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();
        try {

            ArrayList<Long> arrayList = new ArrayList<>();
            int arrayLen = 10;
            for (int i = 0; i < arrayLen; i++) {
                arrayList.add(keyGenerateService.keyGenerate());
            }

            result.put("success", true);
            result.put("result", arrayList);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @Override
    public BasicService<Image> getBasicService() throws Exception {
        return appImageService;
    }

    /**
     * 前端文件流的形式上传文件
     * @author Lizt
     * @date 2019/1/25
     */
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> fileUpload(@RequestParam MultipartFile file, // 获取的MultipartFile文件，参数为'file',
                                          HttpServletRequest request, HttpServletResponse respone) {
        Long parentid = Long.parseLong(request.getParameter("parentid"));
        String module = request.getParameter("module");
        Map<String, Object> result = new HashMap<String, Object>();
        Image record = new Image();
        try {
            if (null == parentid) {
                throw new ServiceException("IMAGE-001");
            }
            if (file == null) {
                throw new ServiceException("PUBLIC-017");
            }
            if (StringUtils.isBlank(module)) {
                throw new ServiceException("PUBLIC-054");
            }
            record.setModule(module);
            record.setParentid(parentid);
            if (null == record.getId()) {
                record.setId(keyGenerateService.keyGenerate());
            }
            appImageService.upload(file, record);
            record = appImageService.queryById(record);
            result.put("success", "true");
            result.put("result", record);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("result", e.getMessage());
            result.put("success", false);
        }
        return result;
    }
}
